import axios from 'axios';
import {  envConfig } from '@/config';
import { toast, } from '@/utils';
const {baseURL} = envConfig;

type TRequestMethod = 'get' | 'post';

type TAnyRecord = Record<string, any>;

interface IReqConfig {
    timeout?: number;
    headers?: {
        [propName: string]: any;
    };
    // 成功回调返回response.data
    originalData?: boolean;
    // 成功回调直接返回response
    originalResponse?: boolean;
    // disable默认错误提示（自己处理错误）
    disableErrorToast?: boolean;
    [propName: string]: any;
}

interface IHttp {
    request(type: TRequestMethod, url: string, params?: TAnyRecord, config?: IReqConfig): Promise<any>;
    get(url: string, params?: TAnyRecord, options?: IReqConfig): Promise<any>;
    post(url: string, params?: TAnyRecord, options?: IReqConfig): Promise<any>;
}

const CODE = {
    SUCCESS: '操作成功',
    NOT_LOGIN: '100002',
    OTHER_ERROR: '999999',
};

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

const instance = axios.create({
    baseURL,
    timeout: 20000,
    withCredentials: true
});

instance.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
instance.interceptors.request.use(conf => conf);
instance.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    const status = Number(error?.status);
    if (!isNaN(status) && status >= 500 || !status) {
        toast('网络服务异常，请稍后再试~');
        console.warn(error);
    }
    return Promise.reject(error);
});

const http: IHttp = {
    async request(type, url, params, config = {}) {
        // const uid = uuid();
        config.headers = {
            ...config.headers,
        };

        params = params || {};

        let axiosConfig;
        if (type === 'post') {
            axiosConfig = [params, config];
        } else {
            config.params = params;
            axiosConfig = [config];
        }

        const response = await instance[type](url, ...axiosConfig);

        if (config?.originalResponse) {
            return response;
        }
        if (config?.originalData) {
            return response.data;
        }

        let { data: res } = response;
        let { msg, data } = res;
        msg = String(msg);
        if (msg === CODE.SUCCESS) return data;

        if (msg === CODE.NOT_LOGIN) {
            // to login
        } else if (config?.disableErrorToast !== true) {
            toast.error(res.message || '网络异常，请稍后再试');
        }

        return Promise.reject(res);
    },
    async post(url, params, ...options) {
        return this.request('post', url, params, ...options);
    },
    async get(url, params, ...options) {
        return this.request('get', url, params, ...options);
    },
};

export default http;
